package com.igame.Service.impl;

import com.igame.Service.CommonService;
import com.igame.Utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Override
    public String upload(MultipartFile file) {
        final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return "文件大小大于5MB，请选择其他文件";
        }

        try {
            // 获取文件原始文件名
            String originalFilename = file.getOriginalFilename();

            // 截取文件原始名的后缀名 如 jpg png
            assert originalFilename != null;
            String lastName = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 使用uuid重命名文件 防止文件名重复
            String objName = UUID.randomUUID().toString() + lastName;

            // 上传文件到阿里云 OSS
            return aliOssUtil.upload(file.getBytes(), objName);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return "文件上传失败: " + e.getMessage();
        }
    }
}
